package service;

import com.smarthouse.model.User;
import com.smarthouse.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    public boolean login(String username, String password) {
        String sql = "SELECT * FROM users WHERE username = ?";
        try {
            User user = jdbcTemplate.queryForObject(sql, 
                new Object[]{username},
                (rs, rowNum) -> new User(
                    rs.getLong("id"),
                    rs.getString("username"),
                    rs.getString("password")
                )
            );
            
            return user != null && passwordEncoder.matches(password, user.getPassword());
        } catch (EmptyResultDataAccessException e) {
            return false;
        }
    }

    public void register(String username, String password) {
        String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
        try {
            jdbcTemplate.update(sql, username, passwordEncoder.encode(password));
        } catch (Exception e) {
            throw new RuntimeException("用户名已存在");
        }
    }
} 